/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.aliyun.oss;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.google.common.base.Throwables;
import com.sfkj.walk.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class AliyunOssService {

    @Autowired
    private AliyunOssProperties properties;

    public UploadFile upload(UploadFile file) {
        String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(file.getBytes()));
        // TODO md5验证

        // 创建ClientConfiguration实例，按照您的需要修改默认参数
        ClientConfiguration conf = new ClientConfiguration();
        // 开启支持CNAME选项
        conf.setSupportCname(true);

        // 创建OSSClient实例
        OSSClient client = new OSSClient(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret(), conf);

        // 上传
        try {
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(file.getSize());
            meta.setContentType(file.getContentType());
            meta.setContentMD5(md5);

            meta.setContentDisposition("attachment;filename=" + file.getOriginalFilename());
            Map<String, String> userMetadata = new HashMap<>();
            userMetadata.put("filename", file.getOriginalFilename());
            userMetadata.putAll(file.getMetadata());
            meta.setUserMetadata(userMetadata);

            client.putObject(properties.getBucket(), file.getFullFileName(), file.getInputStream(), meta);

        } catch (Exception e) {
            String message = "上传文件到OSS失败:" + Throwables.getRootCause(e).getMessage();
            throw new SystemException(message);
        } finally {
            // 关闭client
            client.shutdown();
        }

        file.setUrl(properties.getDomain() + (StringUtils.isBlank(properties.getDomain()) ? "" : "/") + file.getFullFileName());

        return file;
    }

    public UploadFile getFile(String fullFileName) {
        // 创建ClientConfiguration实例，按照您的需要修改默认参数
        ClientConfiguration conf = new ClientConfiguration();
        // 开启支持CNAME选项
        conf.setSupportCname(true);
        // 创建OSSClient实例
        OSSClient client = new OSSClient(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret(), conf);

        UploadFile file = new UploadFile();
        // 下载
        try {
            OSSObject ossObject = client.getObject(properties.getBucket(), fullFileName);
            ObjectMetadata metadata = ossObject.getObjectMetadata();
            Map<String, String> userMetadata = metadata.getUserMetadata();

            file.setOriginalFilename(userMetadata.get("filename"));
            file.setContentType(metadata.getContentType());
            file.setContentMd5(metadata.getContentMD5());
            file.setContentDisposition(metadata.getContentDisposition());
            file.setSize(metadata.getContentLength());
            file.setInputStream(ossObject.getObjectContent());
            file.setBytes(FileCopyUtils.copyToByteArray(file.getInputStream()));
            file.setFullFileName(ossObject.getKey());
            if (MapUtils.isNotEmpty(userMetadata)) {
                file.setMetadata(userMetadata);
            }

        } catch (Exception e) {
            String message = "下载文件到OSS失败:" + Throwables.getRootCause(e).getMessage();
            throw new SystemException(message);
        } finally {
            // 关闭client
            client.shutdown();
        }

        file.setUrl(properties.getDomain() + "/" + file.getFullFileName());

        return file;
    }

}
